# -*-coding: Utf-8 -*-
# @Project_name :  django_test
# @File         :  zip_util.py
# @Author       :  Gu sir
# @Email        :  974547007@qq.com
# @Motto        :  Python is the best computer language in the world!
# Time          :  2023/4/8 16:02
import io
import os
import zipfile


def do_zip_compress(dirpath):
    """
    压缩文件夹
    """
    print("原始文件夹路径：" + dirpath)
    output_name = f"{dirpath}.zip"
    parent_name = os.path.dirname(dirpath)
    print("压缩文件夹目录：", parent_name)
    zip = zipfile.ZipFile(output_name, "w", zipfile.ZIP_DEFLATED)
    # 多层级压缩
    for root, dirs, files in os.walk(dirpath):
        for file in files:
            if str(file).startswith("~$"):
                continue
            filepath = os.path.join(root, file)
            print("压缩文件路径：" + filepath)
            writepath = os.path.relpath(filepath, parent_name)
            zip.write(filepath, writepath)
    zip.close()
    return output_name


def zip2bytes(dirpath,
              compression=zipfile.ZIP_DEFLATED,
              compresslevel=1,
              **kwargs):
    """
    将多个文件压缩到一个zip bytes中， 不存本地文件
    返回的zip bytes 可被open("test.zip", "wb")写成本地文件
    :param file_map: {filename: content} -> {"test.xml": "xxx"}
    :param compression: ZIP_DEFLATED zip压缩, ZIP_STORED不压缩
    :param compresslevel: 压缩等级, 只在compression=ZIP_DEFLATED时有效
    :param kwargs: zipfile.ZipFile
    :return: zip bytes
    """
    parent_name = os.path.dirname(dirpath)
    if compression == zipfile.ZIP_STORED:
        compresslevel = None
    kwargs["compression"] = compression
    kwargs["compresslevel"] = compresslevel
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w", **kwargs) as z:
        # 多层级压缩
        for root, dirs, files in os.walk(dirpath):
            for file in files:
                if str(file).startswith("~$"):
                    continue
                filepath = os.path.join(root, file)
                print("压缩文件路径：" + filepath)
                writepath = os.path.relpath(filepath, parent_name)
                z.write(filepath, writepath)
    buffer.seek(0)
    return buffer
